﻿using DeviceMaintainGIS.Entity;
using DeviceMaintainGIS.Model;
using DeviceMaintainGIS.Model.Replace;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Web.Script.Serialization;

namespace DeviceMaintainGIS.BLL.Device
{
    /// <summary>
    /// 维修换新操作
    /// </summary>
    public class DeviceService
    {
        /// <summary>
        /// 根据条件获取维修换新信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnListVM<ReplaceResponse> GetRemoteInfoList(ReplaceSelectRequest request)
        {
            ReturnListVM<ReplaceResponse> list = new ReturnListVM<ReplaceResponse>();

            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from k in Entities.RepairRelation_Tab//.Where(i => i.State == 1)
                           join f in Entities.Replace_Tab on k.RelationGuid equals f.Guid
                           into tmpField
                           let a = tmpField.FirstOrDefault()
                           join u in Entities.FieldInfo_Tab on k.RelationGuid equals u.RRGuid
                            into tmpFieldInfo
                           from b in tmpFieldInfo.DefaultIfEmpty()
                           join ur in Entities.tbUser on k.OperatorID equals ur.ID
                            into tmptbUser
                           from tbUser in tmptbUser.DefaultIfEmpty()
                           select new ReplaceResponse
                           {
                               RepairId = a.RepairId,
                               FixUp = a.FixUp,
                               Guid = a.Guid,
                               AddTime = a.AddTime,
                               Step = k.Step,
                               State = k.State,
                               userIDs = b == null ? "" : b.userIDs,
                               PlateNumber = b == null ? "" : b.PlateNumber,
                               SceneTime = b == null ? System.DateTime.Now : b.SceneTime,
                               EndTime = b == null ? System.DateTime.Now : b.EndTime,
                               OperatorID = k.OperatorID,
                               OperatorName = tbUser == null ? "" : tbUser.RealName,
                           };
                //报修编号查询条件
                if (!string.IsNullOrEmpty(request.RepairId))
                {
                    linq = linq.Where(i => i.RepairId == request.RepairId);
                }
                //步骤查询条件
                if (request.Step != -1)
                {
                    linq = linq.Where(i => i.Step == request.Step);
                }
                //if (request.NextOperatorID>0)
                //{
                //    linq = linq.Where(i => i.NextOperatorID == request.NextOperatorID);
                //} 
                list.TotalCount = linq.Count();
                List<ReplaceResponse> ReplaceResponseList = linq.OrderByDescending(i => i.AddTime).Take(request.PagesSize * request.PageIndex).Skip(request.PagesSize * (request.PageIndex - 1)).ToList();
                //循环查询每个现场服务的图片集合
                foreach (ReplaceResponse rr in ReplaceResponseList)
                {
                    var ReplaceDevInfolinq = from k in Entities.ReplaceInfo_Tab.Where(i => i.Guid == rr.Guid)
                                             join f in Entities.DevInfo_Tab on k.DeviceId equals f.DeviceId
                                             into tmpDevInfoTab
                                             let d = tmpDevInfoTab.FirstOrDefault()
                                             join ur in Entities.tbUser on k.PRMuserID equals ur.ID
                                             into tmptbUser
                                             from tbUser in tmptbUser.DefaultIfEmpty()
                                             select new ReplaceDevInfo
                                             {
                                                 RepairOrChange = k.RepairOrChange,
                                                 DeviceId = k.DeviceId,
                                                 Describe = k.Describe,
                                                 PRMuserID = k.PRMuserID,
                                                 Price = k.Price,
                                                 ReturnTime = k.ReturnTime,
                                                 DeviceName = d.DeviceName,
                                                 PRMuserName = tbUser == null ? "" : tbUser.RealName,
                                                 //AddTime = k.DateTime.Now,
                                             };
                    rr.ReplaceInfoList = ReplaceDevInfolinq.ToList();
                }
                list.List = ReplaceResponseList;
                list.PageIndex = request.PageIndex;
                list.PagesSize = request.PagesSize;
            }
            return list;
        }
        /// <summary>
        /// 维修换新编辑或添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnMessageVM RemoteOperation(ReplaceRequest request)
        {
            ReturnMessageVM rm = new ReturnMessageVM();
            if (string.IsNullOrEmpty(request.Guid))
            {
                rm = RemoteOperationAdd(request);
            }
            else
            {
                rm = RemoteOperationEdit(request);
            }
            return rm;
        }
        /// <summary>
        /// 维修换新添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
            // POST: api/Replace
        public ReturnMessageVM RemoteOperationAdd(ReplaceRequest request)
        {
            ReturnMessageVM rm = new ReturnMessageVM();
            rm.Succeed = true;
            //远程服务表
            string newID = Guid.NewGuid().ToString();
            rm.Message = newID;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    try
                    {
                        Replace_Tab ReplaceTab = new Replace_Tab();
                        ReplaceTab.RepairId = request.RepairId;
                        ReplaceTab.FixUp = request.FixUp;
                        ReplaceTab.AddTime = System.DateTime.Now;
                        ReplaceTab.Guid = newID;
                        Entities.Replace_Tab.Add(ReplaceTab);
                        Entities.Entry<Replace_Tab>(ReplaceTab).State = System.Data.Entity.EntityState.Added;
                        //1去现场 2不去现场 
                        if (request.FixUp == 1)
                        {
                            //出现场信息表
                            FieldInfo_Tab fi = new FieldInfo_Tab();
                            fi.RRGuid = newID;
                            fi.userIDs = request.userIDs;
                            fi.PlateNumber = request.PlateNumber;
                            fi.SceneTime = request.SceneTime;
                            fi.EndTime = request.EndTime;
                            Entities.FieldInfo_Tab.Add(fi);
                            Entities.Entry<FieldInfo_Tab>(fi).State = System.Data.Entity.EntityState.Added;
                        }
                        //else
                        //{
                        //    //报修结束表
                        //    RepairEnd_Tab ret = new RepairEnd_Tab();
                        //    ret.Guid = Guid.NewGuid().ToString();
                        //    ret.RepairId = request.RepairId;
                        //    ret.EndTime = System.DateTime.Now;
                        //    Entities.RepairEnd_Tab.Add(ret);
                        //    Entities.Entry<RepairEnd_Tab>(ret).State = System.Data.Entity.EntityState.Added;
                        //}
                        //判断更换或维修设备json是否为空
                        if (request.Devs != null && request.Devs.Count > 0)
                        {
                            //JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                            //List<ReplaceDevInfo> ReplaceDevList = jsonSerialize.Deserialize<List<ReplaceDevInfo>>(request.Devs);
                            foreach (ReplaceDevInfo rdi in request.Devs)
                            {
                                ReplaceInfo_Tab rit = new ReplaceInfo_Tab();
                                string ReplaceInfonewID = Guid.NewGuid().ToString();
                                rit.Rguid = ReplaceInfonewID;
                                rit.Guid = newID;
                                rit.RepairOrChange = rdi.RepairOrChange;
                                rit.DeviceId = rdi.DeviceId;
                                rit.Describe = rdi.Describe;
                                rit.PRMuserID = rdi.PRMuserID;
                                rit.Price = rdi.Price;
                                rit.ReturnTime = rdi.ReturnTime;
                                rit.AddTime = System.DateTime.Now;
                                Entities.ReplaceInfo_Tab.Add(rit);
                                Entities.Entry<ReplaceInfo_Tab>(rit).State = System.Data.Entity.EntityState.Added;
                            }
                        }
                        //上一级保修关系更改
                        RepairRelation_Tab stepRepairRelation = Entities.RepairRelation_Tab.Where(i => i.RepairId == request.RepairId && i.Step == (request.Step - 1) && i.State == 0).FirstOrDefault();
                        if (stepRepairRelation != null && request.State != 0)
                        {
                            stepRepairRelation.State = 1;
                            Entities.RepairRelation_Tab.Add(stepRepairRelation);
                            Entities.Entry<RepairRelation_Tab>(stepRepairRelation).State = System.Data.Entity.EntityState.Modified;
                        }
                        //报修关系表
                        RepairRelation_Tab rrt = new RepairRelation_Tab();

                        rrt.RepairId = request.RepairId;
                        rrt.AddTime = System.DateTime.Now;
                        rrt.TableName = "Replace_Tab";
                        rrt.RelationGuid = newID;
                        rrt.Step = request.Step;
                        rrt.OperatorID = request.OperatorID;
                        rrt.NextOperatorID = request.NextOperatorID;
                        //结束流程
                        if (request.State == -1)
                        {
                            rrt.State = 1;
                            rrt.Operator = -1;
                            rrt.TableName = "RepairEnd_Tab";

                            //报修结束表
                            RepairEnd_Tab ret = new RepairEnd_Tab();
                            ret.Guid = Guid.NewGuid().ToString();
                            ret.RepairId = request.RepairId;
                            ret.EndTime = System.DateTime.Now;
                            Entities.RepairEnd_Tab.Add(ret);
                            Entities.Entry<RepairEnd_Tab>(ret).State = System.Data.Entity.EntityState.Added;
                        }
                        else
                        {
                            rrt.State = request.State == 1 ? 0 : 2;
                            //rrt.Operator = 3;
                            //如果不去现场 又不结束 流程直接到维修换新
                            if (request.FixUp == 1)
                            {
                                rrt.Operator = 3;
                            }
                            else
                            {
                                rrt.Operator = 4;
                            }
                        }
                        Entities.RepairRelation_Tab.Add(rrt);
                        Entities.Entry<RepairRelation_Tab>(rrt).State = System.Data.Entity.EntityState.Added;

                        Entities.SaveChanges();
                        //提交事务
                        transaction.Complete();
                    }
                    catch (Exception ex)
                    {
                        rm.Succeed = false;
                        rm.Message = "入库失败";
                    }
                }
            }

            return rm;
        }
        /// <summary>
        /// 维修换新保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnMessageVM RemoteOperationEdit(ReplaceRequest request)
        {
            ReturnMessageVM rm = new ReturnMessageVM();
            rm.Succeed = true;


            //远程服务表
            string newID = request.Guid;
            rm.Message = newID;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    try
                    {
                        Replace_Tab ReplaceTab = new Replace_Tab();
                        ReplaceTab.RepairId = request.RepairId;
                        ReplaceTab.FixUp = request.FixUp;
                        ReplaceTab.AddTime = System.DateTime.Now;
                        ReplaceTab.Guid = newID;
                        Entities.Replace_Tab.Add(ReplaceTab);
                        Entities.Entry<Replace_Tab>(ReplaceTab).State = System.Data.Entity.EntityState.Added;
                        //1去现场 2不去现场 
                        if (request.FixUp == 1)
                        {
                            //出现场信息表
                            FieldInfo_Tab fi = new FieldInfo_Tab();
                            fi.RRGuid = newID;
                            fi.userIDs = request.userIDs;
                            fi.PlateNumber = request.PlateNumber;
                            fi.SceneTime = request.SceneTime;
                            fi.EndTime = request.EndTime;
                            Entities.FieldInfo_Tab.Add(fi);
                            Entities.Entry<FieldInfo_Tab>(fi).State = System.Data.Entity.EntityState.Added;
                        }
                        //else
                        //{
                        //    //报修结束表
                        //    RepairEnd_Tab ret = new RepairEnd_Tab();
                        //    ret.Guid = Guid.NewGuid().ToString();
                        //    ret.RepairId = request.RepairId;
                        //    ret.EndTime = System.DateTime.Now;
                        //    Entities.RepairEnd_Tab.Add(ret);
                        //    Entities.Entry<RepairEnd_Tab>(ret).State = System.Data.Entity.EntityState.Added;
                        //}
                        //判断更换或维修设备json是否为空
                        if (request.Devs != null && request.Devs.Count > 0)
                        {
                            //JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                            //List<ReplaceDevInfo> ReplaceDevList = jsonSerialize.Deserialize<List<ReplaceDevInfo>>(request.Devs);
                            foreach (ReplaceDevInfo rdi in request.Devs)
                            {
                                ReplaceInfo_Tab rit = new ReplaceInfo_Tab();
                                string ReplaceInfonewID = Guid.NewGuid().ToString();
                                rit.Rguid = ReplaceInfonewID;
                                rit.Guid = newID;
                                rit.RepairOrChange = rdi.RepairOrChange;
                                rit.DeviceId = rdi.DeviceId;
                                rit.Describe = rdi.Describe;
                                rit.PRMuserID = rdi.PRMuserID;
                                rit.Price = rdi.Price;
                                rit.ReturnTime = rdi.ReturnTime;
                                rit.AddTime = System.DateTime.Now;
                                Entities.ReplaceInfo_Tab.Add(rit);
                                Entities.Entry<ReplaceInfo_Tab>(rit).State = System.Data.Entity.EntityState.Added;
                            }
                        }
                        //上一级保修关系更改
                        RepairRelation_Tab stepRepairRelation = Entities.RepairRelation_Tab.Where(i => i.RepairId == request.RepairId && i.Step == (request.Step - 1) && i.State == 0).FirstOrDefault();
                        if (stepRepairRelation != null && request.State != 0)
                        {
                            stepRepairRelation.State = 1;
                            Entities.RepairRelation_Tab.Add(stepRepairRelation);
                            Entities.Entry<RepairRelation_Tab>(stepRepairRelation).State = System.Data.Entity.EntityState.Modified;
                        }
                        //报修关系表
                        RepairRelation_Tab rrt = new RepairRelation_Tab();

                        rrt.RepairId = request.RepairId;
                        rrt.AddTime = System.DateTime.Now;
                        rrt.TableName = "Replace_Tab";
                        rrt.RelationGuid = newID;
                        rrt.Step = request.Step;
                        rrt.OperatorID = request.OperatorID;
                        rrt.NextOperatorID = request.NextOperatorID;
                        //结束流程
                        //if (request.FixUp == 2)
                        //{
                        //    rrt.State = 1;
                        //    rrt.Operator = -1;
                        //    rrt.TableName = "RepairEnd_Tab";
                        //}
                        if (request.State == -1)
                        {
                            rrt.State = 1;
                            rrt.Operator = -1;
                            rrt.TableName = "RepairEnd_Tab";

                            //报修结束表
                            RepairEnd_Tab ret = new RepairEnd_Tab();
                            ret.Guid = Guid.NewGuid().ToString();
                            ret.RepairId = request.RepairId;
                            ret.EndTime = System.DateTime.Now;
                            Entities.RepairEnd_Tab.Add(ret);
                            Entities.Entry<RepairEnd_Tab>(ret).State = System.Data.Entity.EntityState.Added;
                        }
                        else
                        {
                            rrt.State = request.State == 1 ? 0 : 2;
                            //如果不去现场 又不结束 流程直接到维修换新
                            if (request.FixUp == 1)
                            {
                                rrt.Operator = 3;
                            }
                            else
                            {
                                rrt.Operator = 4;
                            }
                        }
                        Entities.RepairRelation_Tab.Add(rrt);
                        Entities.Entry<RepairRelation_Tab>(rrt).State = System.Data.Entity.EntityState.Added;

                        Entities.SaveChanges();
                        //提交事务
                        transaction.Complete();
                    }
                    catch (Exception ex)
                    {
                        rm.Succeed = false;
                        rm.Message = "入库失败";
                    }
                }
            }


            return rm;
        }
    }
}
